# -*- coding=utf-8 -*-
import json
from flask import Flask, render_template
from flask_cors import *
from gevent.pywsgi import WSGIServer
from linux_mac import loadLinuxMac
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
# from Crypto.Util.Padding import unpad
import webbrowser
import asyncio

app = Flask(__name__,template_folder='web')
CORS(app, supports_credentials=True)  # 设置跨域
password = b"1?3Q56g81$34.!78"
iv = b"12a89067.23B3278"


@app.route("/linux_sendMessage")
def sendMessage():
    mac = loadLinuxMac()
    message = ""
    code = 404
    if mac is not None and len(mac) > 2:
        message = "success"
        code = 200
    else:
        message = "fail"
    bean = {"message": message, "code": code, "data": encrypt(mac)}
    json_string = json.dumps(bean)
    return render_template(
        "index.html",
        mac=mac,
        jsonMac=json_string,
    )

def encrypt(data: str):
    aes = AES.new(key=password, mode=AES.MODE_CBC, iv=iv)
    # str转byte
    text_byte = data.encode("utf-8")
    # 补位
    text_byte_pad = pad(text_byte, 16, "pkcs7")
    # 加密
    cipher_byte = aes.encrypt(text_byte_pad)
    result = base64.b64encode(cipher_byte)
    cipher = str(result, "utf-8")
    # print(cipher)
    # plaintext_byte = AES.new(password, AES.MODE_CBC, iv).decrypt(
    #     base64.b64decode(cipher)
    # )
    # unpadtext_byte = unpad(plaintext_byte, 16,"pkcs7")
    # plaintext = str(unpadtext_byte, "utf-8")
    # print(plaintext)
    return cipher

async def startWebBrowser():
    await asyncio.sleep(2)
    webbrowser.open_new('http://localhost:8249/linux_sendMessage')


if __name__ == "__main__":
    print("服务地址：http://localhost:8249/linux_sendMessage")
    # app.run(port=8249)
    # task = asyncio.create_task(startWebBrowser())
    asyncio.run(startWebBrowser())
    server = WSGIServer(("0.0.0.0", 8249), app)
    server.serve_forever()
    
